<script setup lang="ts">
import {DOM_SUF} from "~/const/Lists";
import {useLookupStore} from "~/stores/domainLookup";
import type {FormInstance, FormRules} from "element-plus";

import {CERTIFICATE_TYPE} from "~/const/Maps";
import NuxtLink from "#app/components/nuxt-link";
import {AGREEMENT} from "~/const/agreement";
import {debounceFn} from "~/utils/utils";
import {useLoginStore} from "~/stores/login";
definePageMeta({
  layout:"default",
});
const router=useRouter()
const route=useRoute()
const form=reactive({domain:route.query.domain as string||'',suffix:route.query.suffix?[route.query.suffix]:[]})
const lookup=useLookupStore();
const form1=reactive({
  page:1,
  perpage:10,
})
const domainSearch=ref([]);


const tableData=ref<any[]>([])
const list=computed(()=>{
  if (!form.domain.length) {
    return []
  }
  return (form.suffix.length ? form.suffix:DOM_SUF).slice((form1.page - 1) * form1.perpage, (form1.page * form1.perpage)).map(item => ({
    name: `${form.domain}${item}`,
  }))
})
watchEffect(()=>{
  tableData.value=list.value;
})
const total=computed(()=>{
  if(!form.domain.length) return 0;
  return form.suffix.length?form.suffix.length:DOM_SUF.length
})
const search= async (type?:string)=>{
  if(!form.domain) return ElMessage.error('请输入域名')

  const tmp=list.value.filter(item=>!lookup.list[item.name]).map(item=>`.${item.name.split('.')[1]}`);
  if(tmp.length===0) return

  const {data,code}=await useGet('/west/queryDomain',{domain:form.domain,suffix:tmp.join(',')})
  if(code===200){
    domainSearch.value.push(form.domain);
    //@ts-ignore
    lookup.setList(data);
  }
}
const searchDeb= debounceFn(search,1000)
const inputSearch=()=>{
  form1.page=1;
  searchDeb()
}
const current=ref('');
const showWhois=ref();
const registerRef=ref<FormInstance>()
const rules=reactive<FormRules>({
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
  ],
  regyear:[
    { required: true, message: '请输入注册年限', trigger: 'blur' },
    { pattern:/^\d+$/,message:'注册年限必须为数字',trigger:'blur'}
  ],
  id:[
      //数据库模版ID
    { required: true, message: '请输入模版ID', trigger: 'blur' },
  ],
  check:[
    { required: true, message: '请同意协议', trigger: 'blur' },
    { validator:(rule, value, callback)=>{
        if(!value){
          callback(new Error('请同意协议'))
        }else{
          callback()
        }
      },trigger:'blur'}

  ]

})
const register=ref({
  domain:'',
  regyear:1,
  id:'',
  check:true,
});
const temps=ref([]);
const refresh=ref(()=>{})
const getTemplateList=async ()=>{
  const {data,code}=await useGet('/west/getTemplateList',{limit:100,page:1})
  if(code==200){
   temps.value=data?.data;
    register.value.id=(data?.data.find(item=>item.is_default==1)||data?.data[0]).id
    refresh.value=ref;
  }
  return temps;
}
const login=useLoginStore();
const registerDo=()=>{
  if(!route.path.startsWith('http')){
    register.value.domain=register.value.domain+'.test';
    if(!register.value.domain.includes('.test')) return ElMessage.error('域名要带后缀测试后缀，上线后移出')
  }
  if(!registerRef.value) return ElMessage.error('请等待表单加载完成')
  registerRef.value?.validate(async (valid,invalidFields) => {
    if (valid) {
      const {data,code}=await usePost('/west/registerDomain',register.value);
      if(code==200){
        ElMessage.success('注册成功');
        login.refreshInfo();
        registerShow.value=false;
        registerRef.value?.resetFields();
      }
    } else {
      showFieldsError(invalidFields)
    }
  });
}
const navigateList={
  'domainSuffix.html':'价格总览'
}
const regPrice=ref()
const regDisable=ref(false)
const queryPrice=async ()=>{
  const {data,code}=await usePost('/west/queryPrice',register.value)
  if(code==200){
    regPrice.value=data.buyprice?data.buyprice:'改域已被注册';
    regDisable.value=data.buyprice?false:true;
  }
}
const registerShow=ref(false);
const showRegDialog=(row)=>{
  register.value.domain=row.name;
  registerShow.value=true;
}
watchEffect(()=>{
  if(register.value.domain&&register.value.regyear){
    regDisable.value=true;
    queryPrice()
  }
})
watchEffect(()=>{
  if(register.value.domain){
    getTemplateList()
  }
})
</script>

<template>
<div>
  <div class="bg-white">
    <div class="w-[1200px] grid grid-cols-7 gap-2 mx-auto py-5 flex" >
      <div class="col-span-5">
        <div class="w-[800px] mx-auto flex">
          <el-input size="large" v-model="form.domain" placeholder="请输入你要注册的域名" @input="inputSearch">
            <template #append>
              <el-select size="large" v-model="form.suffix" placeholder="请选择后缀" style="width: 200px;" multiple collapse-tags filterable>
                <el-option label="后缀" value=""></el-option>
                <el-option :label="item" :value="item" v-for="item in DOM_SUF"></el-option>
              </el-select>
            </template>
          </el-input>
          <el-button type="primary" @click="search('start')" size="large"><span class="px-8">搜索</span></el-button>
        </div>
      </div>
      <div class="col-span-2">
        <el-space spacer="|">
<!--          <el-button text type="primary" size="large" @click="goto(index)" v-for="(item,index) in ['域名续费','域名转入','价格纵览 >']">{{item}}</el-button>-->
          <el-button text type="primary" size="large" v-for="(item,path) in navigateList"><NuxtLink :to="path">{{item}}</NuxtLink>></el-button>
        </el-space>
      </div>
    </div>
  </div>
  <div>
    <div class="w-[1200px] grid grid-cols-7 gap-2 mx-auto py-5 flex">
      <el-card class="col-span-5">
          <div class="p-2 text-green-400">查询列表</div>
          <el-table :data="tableData" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" class="h-[620px] overflow-auto w-full">
            <el-table-column prop="name" label="域名"></el-table-column>
            <el-table-column label="状态">
              <template #default="{row}">
                <template v-if="lookup.list[row.name]">
                  <el-tag v-if="lookup.list[row.name].avail==1" type="success">可注册</el-tag>
                  <el-tag v-else-if="lookup.list[row.name].avail==-1" type="danger">没有资质</el-tag>
                  <el-tag v-else type="danger">不可注册</el-tag>
                </template>
                <el-tag v-else type="info">准备查询</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格">
              <template #default="{row}">
                <div v-if="lookup.list[row.name]">{{lookup.list[row.name]?.price}}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作">
              <template #default="{row}">
                <div v-if="lookup.list[row.name]?.avail==1"><el-button type="primary" @click="showRegDialog(row)">注册</el-button></div>
                <div v-else-if="lookup.list[row.name]?.avail==0">
                  <el-button type="primary">委托购买</el-button>
                  <el-button type="primary"><NuxtLink target="_blank" :to="`/whoisDetail?domain=${row.name}`">whois信息</NuxtLink></el-button>
                </div>
                <div v-else>-</div>

              </template>
            </el-table-column>
          </el-table>
          <MyPage v-model:page="form1.page" v-model:total="total" v-model:perpage="form1.perpage" @change="search"/>
      </el-card>
      <el-dialog v-model="registerShow" title="域名注册信息" width="400px" center>
        <el-form :model="register" :rules="rules" ref="registerRef" label-width="120">
          <el-form-item label="域名" prop="domain">
            <div class="flex">
              <div class="w-[150px]">
                <el-input v-model="register.domain" clearable placeholder="请在查询列表选择域名" @blue="queryPrice" readonly></el-input>
              </div>
              <div class="ml-1">
                <span class="ml text-red-400" v-if="regPrice">¥{{regPrice}}</span>
              </div>
            </div>

          </el-form-item>
          <el-form-item label="注册年限" prop="regyear">
            <div class="w-[150px]">
              <el-select v-model="register.regyear" placeholder="请选择注册年限">
                <el-option :label="`${item}年`" :value="item" v-for="item in 10"></el-option>
              </el-select>
            </div>

          </el-form-item>
          <el-form-item label="模版ID" prop="id">
            <div class="flex">
              <div class="w-[150px]">
                <el-select v-model="register.id" placeholder="请选择模版ID" >
                  <el-option v-for="item in temps" :label="`【${item.c_regtype=='I'?'个人':'企业'}】${item.fullname}`" :value="item.id"></el-option>
                </el-select>
              </div>
              <div v-if="refresh" class="ml-1">
                <el-button @click="getTemplateList" type="primary" text>刷新模版</el-button>
              </div>

            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="register.check">我已阅读并同意<NuxtLink :to="AGREEMENT.域名注册服务条款">《域名注册服务条款》</NuxtLink></el-checkbox>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="registerShow=false">取 消</el-button>
          <el-button type="primary" @click="registerDo" :disabled="regDisable">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>

</div>

</template>

<style scoped lang="scss">

</style>